package com.adong.controller;

import com.adong.bean.Employee;
import com.adong.bean.Msg;
import com.adong.service.EmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    /**
     * 导入
     *
     * @param pn
     * @return
     */
    @RequestMapping("/emps")
    @ResponseBody
    public Msg getEmpWithJson(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {
        PageHelper.startPage(pn, 5);
        List<Employee> employeeList = employeeService.getAll();
        //使用pageInfo包装查询后的，只需要pageInfo交给页面就行了，封装详细的分页信息，包括我们查询出来的数据
        PageInfo<Employee> page = new PageInfo<>(employeeList, 5); //传入连续显示的页数
        return Msg.success().add("pageInfo", page);
    }

    /**
     * 员工保存
     *
     * @return
     */
    @RequestMapping(value = "/emps", method = RequestMethod.POST)
    @ResponseBody
    public Msg saveEmp(@Valid Employee employee, BindingResult result) {

        //后端约束,JSR303约束,格式等数据不正确会将错误信息发送给页面,正常等才会去数据库中保存
        if (result.hasErrors()) {
            System.out.println(2);
            //校验失败,返回失败信息
            Map<String, Object> map = new HashMap<>();
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                //错误字段名,错误信息
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return Msg.fail().add("errorFields", map);

        } else {
            System.out.println(employee.getGender());
            employeeService.saveEmp(employee);
            return Msg.success();
        }


    }


    @ResponseBody
    @RequestMapping("/checkuser")
    public Msg checkUser(@RequestParam("empName") String empName) {
        String regx = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,6})";
        //不符合不使用数据库用户名校验
        if (!empName.matches(regx)) {
            return Msg.fail().add("va_msg", "用户名可以是2-7位中文或者6-16位英文数值的组合");
        }
        boolean b = employeeService.checkUser(empName);
        return b == true ? Msg.success() : Msg.fail().add("va_msg", "用户名不可用");
    }

    /**
     * 查询全部员工数据(分页查询)
     *
     * @return 返回页面
     */
    //@RequestMapping("/emps")
    public String getEmps(@RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) {
        //引入pageHelper分页插件
        //在查询之间只需要调用,传入页码，每页的带下
        PageHelper.startPage(pn, 5);
        List<Employee> employeeList = employeeService.getAll();
        //使用pageInfo包装查询后的，只需要pageInfo交给页面就行了，封装详细的分页信息，包括我们查询出来的数据
        PageInfo<Employee> page = new PageInfo<>(employeeList, 5); //传入连续显示的页数
        model.addAttribute("pageInfo", page);
        return "list";
    }

    /**
     * 查询员工信息和部门信息
     *
     * @param id
     * @return
     */

    @RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Msg getEmp(@PathVariable(value = "id") Integer id) {
        Employee employee = employeeService.getEmp(id);
        return Msg.success().add("emp", employee);

    }

    /**
     * 更新员工信息
     * 直接发送ajax=put形式的请求
     * 请求体中有数据,但是Employee对象封装不上
     * tomcat:请求体中的数据,封装一个mpa, request.getParameter("empName)就会从这个map中获值
     * SpringMVC封装POJO对象的时候,会把每个值request.getParameter("empName")拿到
     * put请求request.getParameter()拿不到,tomcat看到put不会封装请求体中的map,只有post才将请求体封装成map
     * 配置web.xml
     * <filter-class>org.springframework.web.filter.FormContentFilter</filter-class>
     * 将请求体中的数据解析包装成一个map,request被重新包装,request.getParameter()重写,从自己的map里面拿数据
     */

    @RequestMapping(value = "/emp/{empId}", method = RequestMethod.PUT)
    @ResponseBody
    public Msg updateEmp(Employee employee) {
        employeeService.updateEmp(employee);
        return Msg.success();
    }

    /**
     * 删除方法
     * @param ids
     * @return
     */
    @RequestMapping(value = "/emp/{ids}", method = RequestMethod.DELETE)
    @ResponseBody
    public Msg deleteEmp(@PathVariable("ids") String ids) {
        //批量删除
        if (ids.contains("-")) {
            List<Integer> del_ids = new ArrayList<>();
            String[] str_ids = ids.split("-");
            for (String str : str_ids) {
                del_ids.add(Integer.parseInt(str));
            }
            employeeService.deleteBatch(del_ids);
            //单个删除
        } else {
            Integer id = Integer.parseInt(ids);
            employeeService.deleteEmp(id);
        }
        return Msg.success();
    }
}
